package com.yuanhua.sim.client.decoder;

import com.alibaba.fastjson.JSON;
import com.yuanhua.core.base.entity.BaseBean;
import com.yuanhua.sim.client.utils.MapUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 * 解码
 * @author songguoxiang
 * @date: 2022/8/1 16:34
 */
@Slf4j
public class MyDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        log.info("数据解码：{}", byteBuf);
        //1.根据协议取出数据
        //标识符
        int tag=byteBuf.readInt();
        //获取指令
        byte code=byteBuf.readByte();
        //获取数据长度
        int len=byteBuf.readInt();
        byte[] bytes=new byte[len];
        byteBuf.readBytes(bytes);
        //2.根据code获取类型
        Class<? extends BaseBean> c= MapUtils.getBean(code);
        //3.反序列化
        BaseBean baseBean= JSON.parseObject(bytes,c);
 
        list.add(baseBean);
    }
}